<template>
  <slot :pagination="pagination" :data="data" :params="query" :load="load" :loading="loading" :pageChange="pageChange" :reload="reload" :setSort="setSort"></slot>
  <slot name="pagination"/>
</template>

<script setup>
import {ajax} from 'framework'
import {ref,reactive,watch,toRefs} from 'vue'
const {url,dict,pageable,pageSize,method,lazy,transform}=defineProps({
  url:String,
  dict:String,
  pageable:{
    type:Boolean,
    default:false
  },
  pageSize:{
    type:Number,
    default: 10
  },
  method:{
    default:'post',
    type:String
  },
  lazy:{
    type:Boolean,
    default:false
  },
  transform:{
    type:Function,
    default:(data)=>data,
  }
})
const emit=defineEmits(['beforeLoad','load','afterLoad','init'])
const data=ref([])
const query=reactive({})
const pagination=reactive({page:1,size:pageSize,total:0})
const loading=ref(false)
const dataset={
  data,query,pagination,loading
}
let sort=""
function reload(){
  pagination.page=1
  load()
}
function load(){

  if(dict){

  }else{
    let params=Object.assign({},query)
    if(pageable){
      params.pageNo=pagination.page
      params.pageSize=pagination.size
    }else{
      params.skipQueryCount=true
    }
    params.sort=sort
    emit('beforeLoad',params)
    loading.value=true
    ajax[method](url,params).then(r=>{
      let _data= r.data || r.rows
      if(pageable&&_data instanceof Array){
        let dataIdx=0;
        for(let item of _data){
          dataIdx++;
          if(!item._index){
            item._index=(pagination.page-1)*pagination.size+dataIdx
          }
        }
      }
      emit('load',_data)
      _data=transform(_data)
      setData(_data)
      pagination.total= r.total || r.recordCount
      emit('afterLoad',_data)
    }).finally(()=>{
      loading.value=false
    })
  }
}
function pageChange(page){
  if(page){
    pagination.page=page.page
    pagination.size=page.size
  }
  load()
}

function setData(d){
  data.value=d
}
function setSort(v){
  if(v.type==null){
    sort=""
  }else{
    sort=v.prop+" "+v.type
  }
  load()
}
const exposeProp={load,setData,params:query,pagination,reload,loading,setSort,getData(){return data}}
emit('init',exposeProp)
if(!lazy){
  load()
}
defineExpose(exposeProp)

</script>

<style scoped>

</style>
